from django.db import models
from django.utils import timezone
from django.core.validators import MinValueValidator


class ForumUser(models.Model):
    """用户表"""
    username = models.CharField(verbose_name="用户名", max_length=10, unique=True)
    password = models.CharField(verbose_name="密码", max_length=20)
    email = models.CharField(verbose_name="邮箱", max_length=20)
    age = models.IntegerField(verbose_name="年龄", default=0, validators=[MinValueValidator(1)])
    is_admin = models.IntegerField(verbose_name="管理员", default=0)
    sex_choices = (
        (1, "男"),
        (2, "女"),
        (3, "保密"),
    )
    sex = models.SmallIntegerField(verbose_name="性别", choices=sex_choices)
    registerDate = models.DateField(verbose_name="注册时间", default=timezone.now)

    def __str__(self):
        return self.username

    def getSex(self):
        if self.sex == 1:
            return "男"
        if self.sex == 2:
            return "女"
        return "保密"


class Post(models.Model):
    """
    帖子表模型
    """
    title = models.CharField(verbose_name="标题", max_length=200)
    content = models.TextField(verbose_name="内容")
    post_time = models.DateTimeField(verbose_name="编辑时间", auto_now_add=True)
    user = models.ForeignKey(ForumUser, on_delete=models.CASCADE, verbose_name="作者")

    class Meta:
        ordering = ["-id"]


class Comment(models.Model):
    """
    评论表模型
    """
    content = models.TextField(verbose_name="内容")
    comment_time = models.DateTimeField(auto_now_add=True, verbose_name="评论时间")
    user = models.ForeignKey(ForumUser, on_delete=models.CASCADE, verbose_name="用户")
    post = models.ForeignKey(Post, on_delete=models.CASCADE, verbose_name="帖子")


class Reply(models.Model):
    """
    回复表模型
    """
    content = models.TextField(verbose_name="内容")
    reply_time = models.DateTimeField(auto_now_add=True, verbose_name="回复时间")
    user = models.ForeignKey(ForumUser, on_delete=models.CASCADE, verbose_name="用户")
    comment = models.ForeignKey(Comment, on_delete=models.CASCADE, verbose_name="评论")


class Like(models.Model):
    """
    点赞表模型
    """
    user = models.ForeignKey(ForumUser, on_delete=models.CASCADE, verbose_name="用户")
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True, verbose_name="贴子")
    # comment = models.ForeignKey(
    #     Comment, on_delete=models.CASCADE, null=True, blank=True, verbose_name="评论"
    # )
    like_time = models.DateTimeField(auto_now_add=True, verbose_name="点赞时间")

    class Meta:
        # 确保每个用户对每个帖子或评论只有一个点赞
        unique_together = ("user", "post")
        # unique_together = ("user", "post", "comment")
